/*
 * JANN - a Java toolkit for creating arbitrary Artificial Neural Networks.
 * 
 * Copyright (c) 2009 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.jann;

import java.util.ArrayList;
import java.util.List;


public class LayerLink {

	protected List<Link> links;
	protected Layer preLayer, postLayer;
	protected Parameters params;
	
	public LayerLink() {
		links = new ArrayList<Link>();
	}
	
	public LayerLink( Layer fromLayer, Layer toLayer ) {
		this();
		setPreLayer(fromLayer);
		setPostLayer(toLayer);
	}
	
	protected void connectAll() {
		Link tmpLink;
		links.clear();
		for ( Neuron pre : preLayer.getNeurons() )
			for ( Neuron post : postLayer.getNeurons() ) {
				tmpLink = new Link(pre, post);
				links.add(tmpLink);
				if ( params != null )
					tmpLink.setParameters(params);
			}		
	}
	
	protected void connectPre() {
		if ( postLayer != null ) {
			disconnectPost();
			connectAll();
		}
	}
	
	protected void connectPost() {
		if ( preLayer != null ) {
			disconnectPre();
			connectAll();
		}
	}	
	
	public List<Link> getLinks() {
		return links;
	}
	
	public Layer getPostLayer() {
		return postLayer;
	}

	public void initWeights() {
		for ( Link l : links )
			l.initWeight();
	}
	
	public void setPostLayer(Layer l) {
		if ( postLayer == l )
			return;
		if ( postLayer != null )
			postLayer.removeInputLink(this);
		postLayer = l;
		if ( postLayer != null ) {
			postLayer.addInputLink(this); 
			connectPost();
		} else
			disconnectPost();
	}

	public Layer getPreLayer() {
		return preLayer;
	}

	public void setPreLayer(Layer l) {
		if ( preLayer == l )
			return;
		if ( preLayer != null )
			preLayer.removeOutputLink(this);
		preLayer = l;
		if ( preLayer != null ) {
			preLayer.addOutputLink(this); 
			connectPre();
		} else
			disconnectPre();
	}
	
	public String getWeightString() {
		String s = "";
		for ( Link l : links )
			s += l.getWeight() + " ";
		return s;
	}
	
	public void setParameters( Parameters params ) {
		this.params = params;
		for ( Link l : links )
			l.setParameters(params);
	}
	
	public int size() {
		return links.size();
	}
	
	protected void disconnectPre() {
		for ( Link l : links )
			l.setPreNeuron(null);
	}
	
	protected void disconnectPost() {
		for ( Link l : links )
			l.setPostNeuron(null);
	}
}
